<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>玩转JAVA正则 | 静待花开</title><meta name="author" content="brad 随风起舞"><meta name="copyright" content="brad 随风起舞"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="上来一个例子这里不讲来历，用途，好处,直接就是怎么用！先看个邮箱验证的例子： String input &#x3D;&quot;^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]&#123;2,&#125;)$&quot;;String emailAddress &#x3D;&quot;xyz@abc-.">
<meta property="og:type" content="article">
<meta property="og:title" content="玩转JAVA正则">
<meta property="og:url" content="https://zhangbo4881820.gitee.io/myblog/posts/21435/index.html">
<meta property="og:site_name" content="静待花开">
<meta property="og:description" content="上来一个例子这里不讲来历，用途，好处,直接就是怎么用！先看个邮箱验证的例子： String input &#x3D;&quot;^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]&#123;2,&#125;)$&quot;;String emailAddress &#x3D;&quot;xyz@abc-.">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2019-10-30T01:57:13.000Z">
<meta property="article:modified_time" content="2023-09-07T09:44:01.882Z">
<meta property="article:author" content="brad 随风起舞">
<meta property="article:tag" content="reg">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/myblog/img/favicon.png"><link rel="canonical" href="https://zhangbo4881820.gitee.io/myblog/posts/21435/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/myblog/css/index.css"><link rel="stylesheet" href="/myblog/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="/myblog/css/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/myblog/',
  algolia: undefined,
  localSearch: {"path":"/myblog/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '玩转JAVA正则',
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2023-09-07 17:44:01'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 7.0.0-rc2"><link rel="alternate" href="/myblog/atom.xml" title="静待花开" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/myblog/archives/"><div class="headline">文章</div><div class="length-num">57</div></a><a href="/myblog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a><a href="/myblog/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/myblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分享</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/myblog/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/myblog/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/myblog/movies/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/myblog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/myblog/" title="静待花开"><span class="site-name">静待花开</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/myblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分享</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/myblog/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/myblog/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/myblog/movies/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/myblog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">玩转JAVA正则</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-10-30T01:57:13.000Z" title="发表于 2019-10-30 09:57:13">2019-10-30</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-09-07T09:44:01.882Z" title="更新于 2023-09-07 17:44:01">2023-09-07</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/myblog/categories/%E6%AD%A3%E5%88%99/">正则</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="玩转JAVA正则"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><h2 id="上来一个例子"><a href="#上来一个例子" class="headerlink" title="上来一个例子"></a>上来一个例子</h2><p><strong>这里不讲来历，用途，好处,直接就是怎么用！先看个邮箱验证的例子：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">String input =&quot;^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]&#123;2,&#125;)$&quot;;</span><br><span class="line">String emailAddress =&quot;xyz@abc-.com&quot;;</span><br><span class="line">Pattern p = Pattern.compile(input);</span><br><span class="line">Matcher m = p.matcher(emailAddress);</span><br><span class="line">System.out.println (&quot;The email 1 matches:&quot;+ m.matches());	//true</span><br></pre></td></tr></table></figure>
<h2 id="常用正则符号"><a href="#常用正则符号" class="headerlink" title="常用正则符号"></a>常用正则符号</h2><ul>
<li>直接字符串<br>  <strong>例如：</strong><br>  <code>Pattern.matches(&quot;test&quot;,&quot;test&quot;);</code> <strong>很下显然要匹配的话reg和要验证的字符串相等才行</strong></li>
<li>字符类<br>  <strong>例如：</strong><br>  <code>[Tt]est</code> 这里[]里的就是字符类，意思就是Test和test都匹配，[]就代表一个字符，里面的内容就是这个字符能匹配的情况<br>  而且[]的位置也就是这个字符的位置，也就是说他后面必须的est.<br>  <strong>下面在举几个例子：</strong><br>  <code>Pattern.matches(&quot;[pqr]&quot;,&quot;abcd&quot;);</code> 这显然false.因为pqr三种可能的字符在abcd里都没有<br>  <code>Pattern.matches(&quot;[pqr]&quot;,&quot;r&quot;);</code>	这就是true r就是在pqr三种里的一种<br>  <code>Pattern.matches(&quot;[pqr]&quot;,&quot;pq&quot;);</code> 这乍一看像真的。其实是<strong>false</strong>,因为[]就只表示一个字符pq是两个。这个<strong>牢记</strong><br>  <strong>字符类表达式写法</strong><ol>
<li><code>^</code> 这个放开始是代表正则表达式的开始。但是当他放在[^]里的时候，他的意思是<strong>取消(Negation)</strong><br> <strong>例如：</strong> <code>[^abc]</code> 他的意思就是除了abc之外，我匹配任何字符。</li>
<li><strong>范围（range)</strong> 首尾之间用<code>-</code>连接就是一个范围内。<br> <strong>例如：</strong> <code>[a-z]</code> 这就是代表a到z范围内都匹配。也就是匹配所有小写字母字符</li>
<li><strong>联合(union)</strong> 意思就是多个表达式放一起用。直接上例子<br> <strong>例如：</strong> <code>[a-d[m-p]]</code> 这意思就是我匹配a到d和m到p的字符。<strong>注意</strong> d到m之间的没有匹配</li>
<li><strong>交叉(Intersection)</strong> 这意思就是求交集。就是两个表达式都有的。<br> <strong>例如:</strong> <code>[a-z&amp;&amp;[d-f]]</code> 这里匹配的是d,e,f. 这就是两个范围里面都含有的部分。</li>
<li><strong>减法(Subtraction):</strong> 意思就是前一个表达式减后面表达式的范围。<br> <strong>例如：</strong> <code>[a-z&amp;&amp;[^m-z]]</code> 这里匹配a到l。达到了做减法效果。原因根据上面知识点自己推导。<br> <strong>在来个例子强化下:</strong> <code>[a-f&amp;&amp;[^a-c]&amp;&amp;[^e]]</code> 这里匹配d,f</li>
</ol>
</li>
</ul>
<h2 id="预先定义的符号类"><a href="#预先定义的符号类" class="headerlink" title="预先定义的符号类"></a>预先定义的符号类</h2><p>表达式|解释<br>-|-	<br>.|等于一个点，匹配任何字符(可能匹配也可能不匹配行终止符)<br>\d|等于一个数。[0-9]<br>\D|等于一个非数字符。[^0-9]<br>\s|等于一个空字符。[\t\n\xoB\f\r]<br>\S|一个非空字符。[^\s]<br>\w|等于一个单词字符<br>\W|一个非单词字符</p>
<p>然而在java中你需要使用双反斜杠：<br><strong>例如:</strong></p>
<pre><code>`String pattern = &quot;\\d\\D\\W\\w\\S\\s&quot;;`
`Pattern.matches(&quot;\\d&quot;,&quot;1&quot;);` 会返回true
`Pattern.matches(&quot;\\D&quot;,&quot;z&quot;);` 会返回true
`Pattern.matches(&quot;.p&quot;,&quot;qp&quot;);` 会返回true
</code></pre>
<h2 id="边界匹配"><a href="#边界匹配" class="headerlink" title="边界匹配"></a>边界匹配</h2><p>表达式|解释<br>-|-	<br>^|相等于一行表达式的开始<br>$|相等于一行表达式的结束<br>\b|相等于单词边界<br>\B|相等于非单词边界<br>\A|相等于输入文本的首端<br>\G|等于上一次匹配的末尾<br>\Z|相等于输入文本的末尾,如果末尾有终止符那么除末尾<br>\z|相等于输入文本的末尾</p>
<p><strong>e.g.</strong></p>
<pre><code>`Pattern.matches(&quot;^Hello$&quot;,&quot;Hello&quot;);` 会返回true,开始和结束之间就是Hello
`Pattern.matches(&quot;^Hello$&quot;,&quot;Namaste!Hello&quot;);` false,不是Hello开头的·
`Pattern.matches(&quot;^Hello$&quot;,&quot;Hello Namaste&quot;);` false,不是以Hello结尾
</code></pre>
<h2 id="数量"><a href="#数量" class="headerlink" title="数量"></a>数量</h2><h3 id="贪婪数量"><a href="#贪婪数量" class="headerlink" title="贪婪数量"></a>贪婪数量</h3><p>贪婪数量将匹配最长的字符串</p>
<p>贪婪数量|解释<br>-|-	<br>x?|相等于匹配0个或1个x<br>x*|相等于匹配0个或多个x<br>x+|相等于匹配1个或多个x<br>x{n}|相等于匹配n个x<br>x{n,}|相等于匹配至少n个x<br>x{n,m}|相等于匹配至少n个但是不超过m个x</p>
<h3 id="勉强数量"><a href="#勉强数量" class="headerlink" title="勉强数量"></a>勉强数量</h3><p>勉强数量将匹配最短的字符串</p>
<p>勉强数量|解释<br>-|-	<br>x??|相等于匹配0个或1个x<br>x*?|相等于匹配0个或多个x<br>x+?|相等于匹配1个或多个x<br>x{n}?|相等于匹配n个x<br>x{n,}?|相等于匹配至少n个x<br>x{n,m}?|相等于匹配至少n个但是不超过m个x</p>
<h3 id="占有数量"><a href="#占有数量" class="headerlink" title="占有数量"></a>占有数量</h3><p>占有故名意思就是匹配整条字符串</p>
<p>占有数量|解释<br>-|-	<br>x?+|相等于匹配0个或1个x<br>x*+|相等于匹配0个或多个x<br>x++|相等于匹配1个或多个x<br>x{n}+|相等于匹配n个x<br>x{n,}+|相等于匹配至少n个x<br>x{n,m}+|相等于匹配至少n个但是不超过m个x</p>
<p><strong>数量代码例子：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">import java.util.regex.Matcher;</span><br><span class="line">import java.util.regex.Pattern;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * create by zhangbo on 2019/10/30 0030</span><br><span class="line"> */</span><br><span class="line">public class DemoForQuantity &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        String regex = &quot;a?&quot;; // to match a in abaa once or not at all</span><br><span class="line">        String regex1 = &quot;a*&quot;;//  to match a in abaa zero or more times</span><br><span class="line">        String regex2 = &quot;a+&quot;;//greedy quantifier to match a in abaa one or more times</span><br><span class="line">        String regex3 = &quot;a&#123;2&#125;&quot;;// greedy quantifier to match every aa sequence in aababbaaaab</span><br><span class="line">        String regex4 = &quot;a&#123;2,&#125;&quot;;//greedy quantifier to match two or more consecutive as in aababbaaaab                                  </span><br><span class="line">        String regex5 = &quot;a&#123;1,3&#125;&quot;;// greedy quantifier to match every a, aa, or aaa in aababbaaaab   </span><br><span class="line">        String regex6 = &quot;a+?&quot;;//reluctant quantifier to match a in abaa one or more times</span><br><span class="line">        String regex7 = &quot;.*+end&quot;;//uses a possessive quantifier to match all characters                              followed by end in This is the end zero or more times</span><br><span class="line"></span><br><span class="line">        String text = &quot;abaa&quot;;</span><br><span class="line">        String text1 =&quot;abaa&quot;;</span><br><span class="line">        String text2 =&quot;abaa&quot;;</span><br><span class="line">        String text3 =&quot;aababbaaaab&quot;;</span><br><span class="line">        String text4 =&quot;aababbaaaab&quot;;</span><br><span class="line">        String text5 =&quot;aababbaaaab&quot;;</span><br><span class="line">        String text6 =&quot;abaa&quot;;</span><br><span class="line">        String text7 =&quot;This is the end&quot;;</span><br><span class="line">        Pattern p1 = Pattern.compile(regex);</span><br><span class="line">        Pattern p2 = Pattern.compile(regex1);</span><br><span class="line">        Pattern p3 = Pattern.compile(regex2);</span><br><span class="line">        Pattern p4 = Pattern.compile(regex3);</span><br><span class="line">        Pattern p5 = Pattern.compile(regex4);</span><br><span class="line">        Pattern p6 = Pattern.compile(regex5);</span><br><span class="line">        Pattern p7 = Pattern.compile(regex6);</span><br><span class="line">        Pattern p8 = Pattern.compile(regex7);</span><br><span class="line">        Matcher m1 = p1.matcher(text);</span><br><span class="line">        Matcher m2 = p2.matcher(text1);</span><br><span class="line">        Matcher m3 = p3.matcher(text2);</span><br><span class="line">        Matcher m4 = p4.matcher(text3);</span><br><span class="line">        Matcher m5 = p5.matcher(text4);</span><br><span class="line">        Matcher m6 = p6.matcher(text5);</span><br><span class="line">        Matcher m7 = p7.matcher(text6);</span><br><span class="line">        Matcher m8 = p8.matcher(text7);</span><br><span class="line"></span><br><span class="line">        while (m1.find()) &#123;</span><br><span class="line">            System.out.println(&quot;m1StartIndex-&gt;&quot;+m1.start()+&quot;EndIndex-&gt;&quot;+m1.end());</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(&quot;------------------------------&quot;);</span><br><span class="line">        while (m2.find()) &#123;</span><br><span class="line">            System.out.println(&quot;m2StartIndex-&gt;&quot;+m2.start()+&quot;EndIndex-&gt;&quot;+m2.end());</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(&quot;------------------------------&quot;);</span><br><span class="line">        while (m3.find()) &#123;</span><br><span class="line">            System.out.println(&quot;m3StartIndex-&gt;&quot;+m3.start()+&quot;EndIndex-&gt;&quot;+m3.end());</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(&quot;------------------------------&quot;);</span><br><span class="line">        while (m4.find()) &#123;</span><br><span class="line">            System.out.println(&quot;m4StartIndex-&gt;&quot;+m4.start()+&quot;EndIndex-&gt;&quot;+m4.end());</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(&quot;------------------------------&quot;);</span><br><span class="line">        while (m5.find()) &#123;</span><br><span class="line">            System.out.println(&quot;m5StartIndex-&gt;&quot;+m5.start()+&quot;EndIndex-&gt;&quot;+m5.end());</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(&quot;------------------------------&quot;);</span><br><span class="line">        while (m6.find()) &#123;</span><br><span class="line">            System.out.println(&quot;m6StartIndex-&gt;&quot;+m6.start()+&quot;EndIndex-&gt;&quot;+m6.end());</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(&quot;------------------------------&quot;);</span><br><span class="line">        while (m7.find()) &#123;</span><br><span class="line">            System.out.println(&quot;m7StartIndex-&gt;&quot;+m7.start()+&quot;EndIndex-&gt;&quot;+m7.end());</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(&quot;------------------------------&quot;);</span><br><span class="line">        while (m8.find()) &#123;</span><br><span class="line">            System.out.println(&quot;m8StartIndex-&gt;&quot;+m8.start()+&quot;EndIndex-&gt;&quot;+m8.end());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><strong>output:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">m1StartIndex-&gt;0EndIndex-&gt;1</span><br><span class="line">m1StartIndex-&gt;1EndIndex-&gt;1</span><br><span class="line">m1StartIndex-&gt;2EndIndex-&gt;3</span><br><span class="line">m1StartIndex-&gt;3EndIndex-&gt;4</span><br><span class="line">m1StartIndex-&gt;4EndIndex-&gt;4</span><br><span class="line">------------------------------</span><br><span class="line">m2StartIndex-&gt;0EndIndex-&gt;1</span><br><span class="line">m2StartIndex-&gt;1EndIndex-&gt;1</span><br><span class="line">m2StartIndex-&gt;2EndIndex-&gt;4</span><br><span class="line">m2StartIndex-&gt;4EndIndex-&gt;4</span><br><span class="line">------------------------------</span><br><span class="line">m3StartIndex-&gt;0EndIndex-&gt;1</span><br><span class="line">m3StartIndex-&gt;2EndIndex-&gt;4</span><br><span class="line">------------------------------</span><br><span class="line">m4StartIndex-&gt;0EndIndex-&gt;2</span><br><span class="line">m4StartIndex-&gt;6EndIndex-&gt;8</span><br><span class="line">m4StartIndex-&gt;8EndIndex-&gt;10</span><br><span class="line">------------------------------</span><br><span class="line">m5StartIndex-&gt;0EndIndex-&gt;2</span><br><span class="line">m5StartIndex-&gt;6EndIndex-&gt;10</span><br><span class="line">------------------------------</span><br><span class="line">m6StartIndex-&gt;0EndIndex-&gt;2</span><br><span class="line">m6StartIndex-&gt;3EndIndex-&gt;4</span><br><span class="line">m6StartIndex-&gt;6EndIndex-&gt;9</span><br><span class="line">m6StartIndex-&gt;9EndIndex-&gt;10</span><br><span class="line">------------------------------</span><br><span class="line">m7StartIndex-&gt;0EndIndex-&gt;1</span><br><span class="line">m7StartIndex-&gt;2EndIndex-&gt;3</span><br><span class="line">m7StartIndex-&gt;3EndIndex-&gt;4</span><br><span class="line">------------------------------</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="特殊结构"><a href="#特殊结构" class="headerlink" title="特殊结构"></a>特殊结构</h2><p>结构|解释<br>-|-	<br>(?<name>x)|x,当作一个捕获组<br>(?:x)|x,当作一个非捕获组<br>(?idmsuxU-idmsuxU)|没什么，就是把匹配标志idmsuxU打开-关闭<br>(?idmsux-idmsux:x)|带有标志idmsux开-关的非捕获组<br>(?&#x3D;x)|x,通过零宽度正向超前<br>(?!x)|x,通过零宽度负向超前<br>(?&lt;&#x3D;x&gt;)|x,通过零宽度正向超前<br>(?&lt;!x)|x,通过零宽度负向超前<br>(?&gt;x)|x,当作一个独立的，非捕获组</p>
<h2 id="分组"><a href="#分组" class="headerlink" title="分组"></a>分组</h2><p>分组是正则很重要的一块。它很灵活的组装模式中的部分，提供不同的匹配。</p>
<p>下面的元字符是正则中重要的部分：</p>
<p><code>|</code>		或者的意思(‘or’也可以表示这意思)<br><code>()</code>	分组的意思</p>
<p>接下来直接来个例子消化下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">import java.util.regex.Matcher;</span><br><span class="line">import java.util.regex.Pattern;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * create by zhangbo on 2019/10/30 0030</span><br><span class="line"> */</span><br><span class="line">public class DemoForGrouping &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        String text = &quot;John writes about this, and John writes about that,&quot; +</span><br><span class="line">                &quot; and John writes about everything. &quot;;</span><br><span class="line">//        找到john组</span><br><span class="line">        String patternString1 = &quot;(John)&quot;;</span><br><span class="line">        Pattern pattern = Pattern.compile(patternString1);</span><br><span class="line">        Matcher matcher = pattern.matcher(text);</span><br><span class="line"></span><br><span class="line">        while (matcher.find()) &#123;</span><br><span class="line">            System.out.println(&quot;found:&quot;+matcher.group(1));//这个1的意思是pattern里的哪个分组，我们这就一个</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>output:</strong></p>
<pre><code>found:John
found:John
found:John
</code></pre>
<h2 id="匹配-验证"><a href="#匹配-验证" class="headerlink" title="匹配&#x2F;验证"></a>匹配&#x2F;验证</h2><p>使用正则是有可能找到匹配的标准模式中的所有文本实例，如果这个模式找到或找不到将返回一个boolean值<br><strong>看代码：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">import java.util.ArrayList;</span><br><span class="line">import java.util.List;</span><br><span class="line">import java.util.regex.Matcher;</span><br><span class="line">import java.util.regex.Pattern;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * create by zhangbo on 2019/10/30 0030</span><br><span class="line"> */</span><br><span class="line">public class ValidateSSH &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        List&lt;String&gt; input = new ArrayList&lt;String&gt;();</span><br><span class="line">        input.add(&quot;123-45-6789&quot;);</span><br><span class="line">        input.add(&quot;9876-5-4321&quot;);</span><br><span class="line">        input.add(&quot;987-65-4321 (attack)&quot;);</span><br><span class="line">        input.add(&quot;987-65-4321 &quot;);</span><br><span class="line">        input.add(&quot;192-83-7465&quot;);</span><br><span class="line">        String patternString = &quot;^(\\d&#123;3&#125;-?\\d&#123;2&#125;-?\\d&#123;4&#125;)$&quot;;</span><br><span class="line">//        字符串的简单验证</span><br><span class="line">        for (String ssn : input) &#123;</span><br><span class="line">            if (ssn.matches(patternString)) &#123;</span><br><span class="line">                System.out.println(&quot;Found good SSN: &quot; + ssn);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">//        使用正则类的Pattern和Matcher 的方法进行验证</span><br><span class="line">        Pattern pattern = Pattern.compile(patternString);</span><br><span class="line">        for (String ssn : input) &#123;</span><br><span class="line">            Matcher matcher = pattern.matcher(ssn);</span><br><span class="line">            if (matcher.matches()) &#123;</span><br><span class="line">                System.out.println(&quot;Found good SSN:&quot;+ssn);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>output:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Found good SSN: 123-45-6789</span><br><span class="line">Found good SSN: 192-83-7465</span><br><span class="line">Found good SSN:123-45-6789</span><br><span class="line">Found good SSN:192-83-7465</span><br></pre></td></tr></table></figure>

<h2 id="提取-捕获"><a href="#提取-捕获" class="headerlink" title="提取&#x2F;捕获"></a>提取&#x2F;捕获</h2><p>正则表达式可以从一个复杂的文本中选出特定的值</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">import java.util.regex.Matcher;</span><br><span class="line">import java.util.regex.Pattern;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * create by zhangbo on 2019/10/30 0030</span><br><span class="line"> */</span><br><span class="line">public class SampleGrouping &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        String input = &quot;I have a kindle, but I like to read book better.&quot;;</span><br><span class="line">        Pattern p = Pattern.compile(&quot;(kindle|read|book|wolf|bear|human)&quot;);</span><br><span class="line">        Matcher m = p.matcher(input);</span><br><span class="line">        while (m.find()) &#123;</span><br><span class="line">            System.out.println(&quot;Found a &quot; + m.group() + &quot;.&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>output:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Found a kindle.</span><br><span class="line">Found a read.</span><br><span class="line">Found a book.</span><br></pre></td></tr></table></figure>
<h2 id="修改-替换"><a href="#修改-替换" class="headerlink" title="修改&#x2F;替换"></a>修改&#x2F;替换</h2><p>使用正则可以将文本中的值替换成新的值，你看下面的单词’userId&#x3D;’，后面是数字，用其他的字符去替换数字</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">import java.util.regex.Matcher;</span><br><span class="line">import java.util.regex.Pattern;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * create by zhangbo on 2019/10/30 0030</span><br><span class="line"> */</span><br><span class="line">public class MaskingDemo &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        String input = &quot;User userId=23421. Some more userId=33432. This is userNum=100&quot;;</span><br><span class="line">        Pattern p = Pattern.compile(&quot;(userId=)(\\d+)&quot;);</span><br><span class="line">        Matcher m = p.matcher(input);</span><br><span class="line">        StringBuffer result = new StringBuffer();</span><br><span class="line">        while (m.find()) &#123;</span><br><span class="line">//          获取第二个分组的值··</span><br><span class="line">            System.out.println(&quot;Masking: &quot; + m.group(2));</span><br><span class="line">//           第一个参数容器，第二参数放入容器的值 往后追加的方式</span><br><span class="line">            m.appendReplacement(result, m.group(1) + &quot;***masked***&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(result);</span><br><span class="line">//       根据result末尾的位置把input里面的text按照此位置之后的text追加到result中</span><br><span class="line">        m.appendTail(result);</span><br><span class="line">        System.out.println(result);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>output:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Masking: 23421</span><br><span class="line">Masking: 33432</span><br><span class="line">User userId=***masked***. Some more userId=***masked***</span><br><span class="line">User userId=***masked***. Some more userId=***masked***. This is userNum=100</span><br></pre></td></tr></table></figure>

<h2 id="匹配多个字符中的一个"><a href="#匹配多个字符中的一个" class="headerlink" title="匹配多个字符中的一个"></a>匹配多个字符中的一个</h2><p>使用[]元字符和不同的字符组合，我们可以匹配已知字符中的许多字符。<strong>例如：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">String input = &quot;I have a cat, dog, mat,cas and rat.&quot;;</span><br><span class="line">Pattern p = Pattern.compile(&quot;(c|d|r|m)[a][ts]&quot;);</span><br><span class="line">Matcher m = p.matcher(input);</span><br><span class="line">List&lt;String&gt; animals = new ArrayList&lt;String&gt;();</span><br><span class="line">while (m.find()) &#123;</span><br><span class="line">    System.out.println(&quot;Found a &quot; + m.group() + &quot;.&quot;);</span><br><span class="line">    animals.add(m.group());</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><strong>output:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Found a cat.</span><br><span class="line">Found a mat.</span><br><span class="line">Found a cas.</span><br><span class="line">Found a rat.</span><br></pre></td></tr></table></figure>
<h2 id="使用一个特殊结构"><a href="#使用一个特殊结构" class="headerlink" title="使用一个特殊结构"></a>使用一个特殊结构</h2><pre><code>当我们想在该字符串的另一个模式之前找到一段文本时，会使用特殊的构造？
</code></pre>
<p>还是要找到一段没有紧随其后的文字？<br>    通常，对于标准字符串搜索，我们需要编写一个稍微复杂的函数以执行所需的确切操作。<br>但是，这可以全部使用正则表达式在一行上完成</p>
<h3 id="Look-Ahead-Look-Behind"><a href="#Look-Ahead-Look-Behind" class="headerlink" title="Look Ahead &amp; Look Behind"></a>Look Ahead &amp; Look Behind</h3><pre><code>先行和后退操作类似于分组，但是这些模式无法捕获值。因此，使用这些构造，不会存储任何值供以后检索，并且它们不会影响组编
</code></pre>
<p>号。前瞻性操作从它们在模式中的位置开始，一直持续到输入的结尾。后向表达式不会向后搜索，而是从模式的开头开始，一直到&#x2F;&#x2F;直到后向表达式为止</p>
<p><strong>例如</strong><br>我们需要去确保输入字符串必须出现”incident”,但是任何地方”theft”不应该被发现。我们可以使用 negative look-ahead 去确保不发生任何事件<br><code>(?!.*theft).*incident.*</code><br>这个表达式在下面展示的行为：</p>
<pre><code>&quot;There was a crime incident&quot;			matches 
&quot;The incident involved a theft&quot;			does not match 
&quot;The theft was a serious incident&quot;		does not match
</code></pre>
<p>这里面的意思就是：我找incident之前先找.*theft 负前瞻就是不能有这个theft找出匹配的。然后在找里面有没有.*incident.*</p>
<h3 id="Positive-Look-Ahead"><a href="#Positive-Look-Ahead" class="headerlink" title="Positive Look Ahead"></a>Positive Look Ahead</h3><p>那么正向前就是你匹配的东西应该被一些模式或者字符串跟随的<br><strong>整向前结构代码例子：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">import java.util.regex.Matcher;</span><br><span class="line">import java.util.regex.Pattern;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * create by zhangbo on 2019/10/30 0030</span><br><span class="line"> */</span><br><span class="line">public class DemoForPositiveLookAhead &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    public static void main(String args[]) &#123;</span><br><span class="line">        String regex = &quot;(?=^255).*&quot;;</span><br><span class="line">        Pattern pattern = Pattern.compile(regex);</span><br><span class="line">        String candidate = &quot;255.0.0.1&quot;;</span><br><span class="line">        String candidate1 = &quot;25.255.0.1&quot;;</span><br><span class="line">        Matcher matcher = pattern.matcher(candidate);</span><br><span class="line">        Matcher matcher1 = pattern.matcher(candidate1);</span><br><span class="line">        String ip = &quot;not found&quot;;</span><br><span class="line">        String ip1= &quot;not found&quot;;</span><br><span class="line"></span><br><span class="line">        if (matcher.find())</span><br><span class="line">            ip = matcher.group();</span><br><span class="line">        String msg = &quot;ip: &quot; + ip;</span><br><span class="line">        System.out.println(msg);</span><br><span class="line"></span><br><span class="line">        if (matcher1.find())</span><br><span class="line">            ip1 = matcher1.group();</span><br><span class="line">        String msg1 = &quot;ip1: &quot; + ip1;</span><br><span class="line">        System.out.println(msg1);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>output:</strong></p>
<pre><code>ip: 255.0.0.1
ip1: not found
</code></pre>
<p>来理解一遍这个语句意思·<code>(?=^255).*</code>  意思是：在匹配除换行外任何字符串之前先找是不是以字符’255’开始的· 咱这后面的表达式没有括号代表就是0组编号。所有goup()默认不填就是0，填0也可以</p>
<h3 id="Negative-Look-Ahead"><a href="#Negative-Look-Ahead" class="headerlink" title="Negative Look Ahead"></a>Negative Look Ahead</h3><p>这个负前瞻的意思就是和正向前相反。就是匹配一些文本之前先确定这个文本里面没有指定的文本在里面</p>
<p><strong>代码例子:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">public class DemoForNegativeLookAhead &#123;</span><br><span class="line"></span><br><span class="line">public static void main(String[] args) &#123;</span><br><span class="line">    String regex = &quot;John (?!Heins)[A-Z]\\w+&quot;;</span><br><span class="line">    Pattern pattern = Pattern.compile(regex);</span><br><span class="line">    String candidate = &quot;I think that John Heins &quot;;</span><br><span class="line">    candidate += &quot;is a fictional character. His real name &quot;;</span><br><span class="line">    candidate += &quot;might be John Jackson, John Westling, &quot;;</span><br><span class="line">    candidate += &quot;or John Holmes for all we know.&quot;;</span><br><span class="line">    Matcher matcher = pattern.matcher(candidate);</span><br><span class="line">    String tmp;</span><br><span class="line">    while (matcher.find()) &#123;</span><br><span class="line">        tmp = matcher.group();</span><br><span class="line">        System.out.println(&quot;MATCH:&quot; + tmp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>output:</strong></p>
<pre><code>MATCH:John Jackson
MATCH:John Westling
MATCH:John Holmes
</code></pre>
<p><strong>正则公式讲解：</strong> </p>
<ul>
<li><code>John (?!Heins)[A-Z]\\w+</code><ol>
<li>john # 意思是字符串以john 开头</li>
<li>(?!Heins) 不应该包含Heins</li>
<li>[A-Z]\w+ 开头的后面第一个字符以大写字母开始后面接1个或者多个单词类型字符。</li>
</ol>
</li>
</ul>
<h3 id="Positive-Look-Behind"><a href="#Positive-Look-Behind" class="headerlink" title="Positive Look Behind"></a>Positive Look Behind</h3><p>如果您要匹配以其他内容开头的内容，则使用正向后查找</p>
<p><strong>直接代码例子</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">public static void main(String[] args) &#123;</span><br><span class="line">    String reg = &quot;(?&lt;=http://)\\S+&quot;;</span><br><span class="line">    Pattern p = Pattern.compile(reg);</span><br><span class="line">    String str = &quot;http://www.a.com. My name&quot;;</span><br><span class="line">    Matcher m = p.matcher(str);</span><br><span class="line">    while (m.find()) &#123;</span><br><span class="line">        String msg = &quot;:&quot; + m.group() + &quot;:&quot;;</span><br><span class="line">        System.out.println(msg);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>output:</strong></p>
<pre><code>:www.a.com.:
</code></pre>
<p><strong>公式解读</strong></p>
<pre><code>(?&lt;=http://)\\S 向后看以 `http://` 开始 然后遭遇一个\\S 空格结束 然后检出的字符要先于 &#39;http://&#39; 那么就剩下 
&#39;www.a.com.&#39;
</code></pre>
<h3 id="Negative-Look-Behind"><a href="#Negative-Look-Behind" class="headerlink" title="Negative Look Behind"></a>Negative Look Behind</h3><p>如果您要匹配不以其他内容开头的内容，则使用负向后查找</p>
<p><strong>代码例子</strong></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">public static void main(String[] args) &#123;</span><br><span class="line">     Pattern p = Pattern.compile(&quot;(?&lt;!Y.&#123;0,40&#125;)X&quot;);</span><br><span class="line">     String txt = &quot;Y less than 40 before X&quot;;</span><br><span class="line">     // 这个公式意思是你不想要x前面以40个字符以内的开头。而这个txt就是在40个字符以内的。所以不匹配    </span><br><span class="line">     Matcher m = p.matcher(txt);</span><br><span class="line">     System.out.println(m.find());</span><br><span class="line">     txt = &quot;Y less ddddddddddddddddddddddddd than 40 before X&quot;;</span><br><span class="line">     //这个txt就是超过40个字符的。所以匹配           </span><br><span class="line">     m.reset(txt);</span><br><span class="line">     System.out.println(m.find());</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p><strong>output:</strong></p>
<pre><code>false
true
</code></pre>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://zhangbo4881820.gitee.io/myblog">brad 随风起舞</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://zhangbo4881820.gitee.io/myblog/posts/21435/">https://zhangbo4881820.gitee.io/myblog/posts/21435/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://zhangbo4881820.gitee.io/myblog" target="_blank">静待花开</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/myblog/tags/reg/">reg</a></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/myblog/posts/42642/" title="玩转JAVA正则2"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">玩转JAVA正则2</div></div></a></div><div class="next-post pull-right"><a href="/myblog/posts/7504/" title="解决git有些文件不能上传"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">解决git有些文件不能上传</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/myblog/posts/42642/" title="玩转JAVA正则2"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-10-31</div><div class="title">玩转JAVA正则2</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/myblog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">brad 随风起舞</div><div class="author-info__description">有些事情需要一辈子的沉淀</div></div><div class="card-info-data site-data is-center"><a href="/myblog/archives/"><div class="headline">文章</div><div class="length-num">57</div></a><a href="/myblog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a><a href="/myblog/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/xxxxx" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:xxxxxx@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%8A%E6%9D%A5%E4%B8%80%E4%B8%AA%E4%BE%8B%E5%AD%90"><span class="toc-number">1.</span> <span class="toc-text">上来一个例子</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E6%AD%A3%E5%88%99%E7%AC%A6%E5%8F%B7"><span class="toc-number">2.</span> <span class="toc-text">常用正则符号</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A2%84%E5%85%88%E5%AE%9A%E4%B9%89%E7%9A%84%E7%AC%A6%E5%8F%B7%E7%B1%BB"><span class="toc-number">3.</span> <span class="toc-text">预先定义的符号类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BE%B9%E7%95%8C%E5%8C%B9%E9%85%8D"><span class="toc-number">4.</span> <span class="toc-text">边界匹配</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E9%87%8F"><span class="toc-number">5.</span> <span class="toc-text">数量</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%B4%AA%E5%A9%AA%E6%95%B0%E9%87%8F"><span class="toc-number">5.1.</span> <span class="toc-text">贪婪数量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8B%89%E5%BC%BA%E6%95%B0%E9%87%8F"><span class="toc-number">5.2.</span> <span class="toc-text">勉强数量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8D%A0%E6%9C%89%E6%95%B0%E9%87%8F"><span class="toc-number">5.3.</span> <span class="toc-text">占有数量</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%89%B9%E6%AE%8A%E7%BB%93%E6%9E%84"><span class="toc-number">6.</span> <span class="toc-text">特殊结构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%86%E7%BB%84"><span class="toc-number">7.</span> <span class="toc-text">分组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8C%B9%E9%85%8D-%E9%AA%8C%E8%AF%81"><span class="toc-number">8.</span> <span class="toc-text">匹配&#x2F;验证</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8F%90%E5%8F%96-%E6%8D%95%E8%8E%B7"><span class="toc-number">9.</span> <span class="toc-text">提取&#x2F;捕获</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BF%AE%E6%94%B9-%E6%9B%BF%E6%8D%A2"><span class="toc-number">10.</span> <span class="toc-text">修改&#x2F;替换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8C%B9%E9%85%8D%E5%A4%9A%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%AD%E7%9A%84%E4%B8%80%E4%B8%AA"><span class="toc-number">11.</span> <span class="toc-text">匹配多个字符中的一个</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E4%B8%80%E4%B8%AA%E7%89%B9%E6%AE%8A%E7%BB%93%E6%9E%84"><span class="toc-number">12.</span> <span class="toc-text">使用一个特殊结构</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Look-Ahead-Look-Behind"><span class="toc-number">12.1.</span> <span class="toc-text">Look Ahead &amp; Look Behind</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Positive-Look-Ahead"><span class="toc-number">12.2.</span> <span class="toc-text">Positive Look Ahead</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Negative-Look-Ahead"><span class="toc-number">12.3.</span> <span class="toc-text">Negative Look Ahead</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Positive-Look-Behind"><span class="toc-number">12.4.</span> <span class="toc-text">Positive Look Behind</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Negative-Look-Behind"><span class="toc-number">12.5.</span> <span class="toc-text">Negative Look Behind</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/15695/" title="jenkins（1）">jenkins（1）</a><time datetime="2023-09-14T02:17:44.000Z" title="发表于 2023-09-14 10:17:44">2023-09-14</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/22012/" title="wsl的Ubuntu子系统（1）">wsl的Ubuntu子系统（1）</a><time datetime="2023-09-13T08:42:19.000Z" title="发表于 2023-09-13 16:42:19">2023-09-13</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/30302/" title="effective-java-(接口优于抽象类)">effective-java-(接口优于抽象类)</a><time datetime="2023-09-12T08:12:48.000Z" title="发表于 2023-09-12 16:12:48">2023-09-12</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/9473/" title="effective-java(创建和销毁对象--组合的形式优于继承)">effective-java(创建和销毁对象--组合的形式优于继承)</a><time datetime="2023-09-11T08:23:19.000Z" title="发表于 2023-09-11 16:23:19">2023-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/16107/" title="Hello World">Hello World</a><time datetime="2023-09-07T09:44:01.910Z" title="发表于 2023-09-07 17:44:01">2023-09-07</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By brad 随风起舞</div><div class="framework-info"><span>框架 </span><a href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/myblog/js/utils.js"></script><script src="/myblog/js/main.js"></script><script src="/myblog/js/fancybox.umd.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/myblog/js/search/local-search.js"></script></div></div></body></html>